import Schema, { Values, Rules } from "async-validator";
import { Context } from "koa";

/*
 * @Author: fishroom
 * @Date: 2022-10-19 14:27:16
 * @LastEditTime: 2022-10-19 15:20:31
 * @FilePath: \koa\app\util\validate.ts
 */
function getObj(ctx: Context) {
  switch (ctx.method) {
    case "GET":
      return ctx.query;
    case "POST":
      return ctx.request.body;
  }
}
async function validate<T extends Values>(
  ctx: Context,
  rules: Rules
): Promise<{ data: T; err: any | null }> {
  try {
    const validator = new Schema(rules);
    let obj = getObj(ctx);
    let { data, error } = await validator.validate(obj);
    return {
      data: obj as T,
      err: null,
    };
  } catch (error) {
    return {
      data: {} as T,
      err: error,
    };
  }
}
export default validate;
